package db.tables;


import java.sql.Statement;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import control.ConnectionManage;


import db.parking.beans.Customer;


public class AdminCustomer {
	
	private static Connection conn = ConnectionManage.getInstance().getConnection();

	/*public static void displayAllRows() throws SQLException {

		String sql = "SELECT *  FROM Comlaints";
		try (
				Statement stmt = conn.createStatement();
				ResultSet rs = stmt.executeQuery(sql);
				){

			System.out.println("Complaints Table:");
			while (rs.next()) {
				StringBuffer bf = new StringBuffer();
				bf.append(rs.getInt("id") + ": ");
				bf.append(rs.getString("username") +", ");
				bf.append(rs.getString("age"));
				System.out.println(bf.toString());
			}
		}
	}
*/
	public static Customer getRow(String cusId,String type) throws SQLException {

		String sql = "SELECT * FROM Customer WHERE cusID = ? AND type = ?";
		ResultSet rs = null;

		try (
				PreparedStatement stmt = conn.prepareStatement(sql);
				){
			stmt.setString(1, cusId);
			stmt.setString(2, type);

			rs = stmt.executeQuery();

			if (rs.next()) {
				Customer bean = new Customer();
				bean.setCusID(cusId);
				bean.setCusName(rs.getString("cusName"));
				bean.setType(rs.getString("type"));
				bean.setUserLevel(rs.getInt("userLevel"));
			
				return bean;
			} else {
				return null;
			}

		} catch (SQLException e) {
			System.err.println(e);
			return null;
		} finally {
			if (rs != null) {
				rs.close();
			}
		}

	}

	public static boolean insert(Customer bean) throws Exception {
    //complaintID is autoIncremented on Insert
		String sql = "INSERT into Customer (cusID , cusName , type , userLevel) " +
				"VALUES (?, ?, ?, ?)";
		ResultSet keys = null;
		try (
				PreparedStatement stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
				) {
			
			stmt.setString(1, bean.getCusID());
			stmt.setString(2, bean.getCusName());
			stmt.setString(3, bean.getType());
			stmt.setInt(4, bean.getUserLevel());
			stmt.executeUpdate();
		
		} catch (SQLException e) {
			System.err.println(e);
			return false;
		} finally{
			if(keys != null)
				keys.close();
		}
		return true;
		
	}
	//update complaint status
	public static boolean update(Customer bean) throws Exception {

		String sql =
				"UPDATE Customer SET " +
				"userLevel = ? " +
				"WHERE id = ?";
		try (
				PreparedStatement stmt = conn.prepareStatement(sql);
				){
			
			stmt.setInt(1,bean.getUserLevel());
			stmt.setString(2,bean.getCusID());
			
			int affected = stmt.executeUpdate();
			if(affected == 1){
				return true;
			}else{
				return false;
			}
			
		}
		catch(SQLException e) {
			System.err.println(e);
			return false;
		}

	}
	
}
